<template>
  <el-page-header>
    <template #breadcrumb>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item >
          <router-link to="/manager/mangerindex" class="menu-router">首页</router-link>
        </el-breadcrumb-item>
        <el-breadcrumb-item
        ><router-link to="/manager/ordermanager" class="menu-router">订单管理</router-link></el-breadcrumb-item
        >
      </el-breadcrumb>
    </template>
    <template #content>

      <span class="text-large font-600 mr-3"> 订单管理 </span>
    </template>
  </el-page-header>
  <el-input
      v-model="input1"
      style="width: 600px"
      size="large"
      placeholder="请输入你想要查询用户的订单编号"
      :suffix-icon="Search"
  />
  <el-table :data="currentPageItems" style="width: 100%" >
    <el-table-column fixed prop="id" label="订单编号" width="150" />
    <el-table-column prop="userId" label="所属用户" width="120" />
    <el-table-column prop="ordertime" label="下单时间" width="120" />
    <el-table-column prop="totalamount" label="下单金额" width="120" />
    <el-table-column prop="status" label="订单状态" width="600" >
      <template #default="{ row }">
        <span :style="{ color:row.color, fontWeight: 'bold' , fontSize: '15px', fontFamily: 'Arial, sans-serif'}">{{ row.status}}</span>
      </template>
    </el-table-column>



    <el-table-column fixed="right" label="操作" width="120" >
      <template #default="{row}">
        <el-button link type="primary" size="small" class="el-button1" @click="showdiglogbutton(row)">修改订单状态</el-button>
        <el-button link type="primary" size="small" @click="touserid(row)">对订单进行通知</el-button>
        <el-button link type="primary" size="small" @click="showdiglog(row)">协助退款</el-button>
        <el-button link type="primary" size="small" @click="getorder(row)">查看订单详情</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
      small
      background
      layout="prev, pager, next"
      :total="totalItems"
      :page-size="pageSize"
      v-model:currentPage="currentPage"
      class="mt-4"
  />
  <el-dialog
      v-model="showdiglog1"
      title="修改订单状态"
      width="600"
      align-center
  >
    <el-segmented v-model="status1" :options="options">
      <template #default="{ item }">
        <div class="flex flex-col items-center gap-2 p-2">
          <el-icon size="20">
            <component :is="item.icon" />
          </el-icon>
          <div>{{ item.label }}</div>
        </div>
      </template>
    </el-segmented>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showdiglog1 = false" type="primary">Cancel</el-button>
        <el-button @click="updateorderstatusByid()" type="success">添加</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
      v-model="showdiglog2"
      title="对订单进行通知"
      width="700"
      align-center
  >
    <el-input
        v-model="message"
        style="width: 600px"
        size="large"
        placeholder="请输入你想要发送的消息"
        :suffix-icon="Search"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showdiglog2 = false" type="primary">Cancel</el-button>
        <el-button @click="sendmessage()" type="success">添加</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
      v-model="centerDialogVisible"
      title="Warning"
      width="500"
      align-center
  >
    <span>如果确认退款,则该订单将取消,请谨慎操作</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="deletorderandorderdetailByorderId(orderId)">
          确认退款
        </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
      v-model="showdiglog3"
      title="订单详情"
      width="800"
      align-center
  >
    <el-table :data="items" style="width: 100%" >
      <el-table-column prop="itemName" label="菜品名称" width="120" />
      <el-table-column prop="price" label="菜品价格" width="120" />
      <el-table-column prop="quantity" label="菜品数量" width="120" />
      <el-table-column
          prop="imageUrl"
          label="图片"
          width="180">
        <template #default="{ row }">
          <el-image
              v-if="row.imageUrl"
              :src="row.imageUrl"
              fit="cover"
              style="width: 50%; height: 50%;">
            <div slot="error" class="image-slot">
              图片加载失败
            </div>
          </el-image>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
</template>

<script setup>
import {
   Bicycle,
  Bowl,
  ForkSpoon,
  Search, SuccessFilled, Wallet,
  WalletFilled,
} from '@element-plus/icons-vue'
import {computed, onMounted, reactive, ref, watch, watchEffect} from "vue";
import {
  deletorderandorderdeTaliByorderIDservice,
  getallorderBybackgroundservice, getaplyedorderdetaibyorderIdservice,
  sendmessageTouserservice,
  updateorderstatusByidservice
} from "@/api/food.js";
import {ElMessage, ElNotification} from "element-plus";
const message=ref()
const input1=ref();
const status1=ref()
const orderId=ref(0)
const showdiglog1=ref(false)
const tableData=reactive([])
const showdiglog2=ref(false)
const userid=ref()
const showdiglog3=ref(false)
const items=reactive([])
const currentPage = ref(1); // 当前页数
const pageSize = ref(10);
const isInitialLoad = ref(false);
const centerDialogVisible=ref(false)
const touserid=(row)=>{
  showdiglog2.value=true
  userid.value=row.userId
  orderId.value=row.id

}
const showdiglog = (row) => {
  centerDialogVisible.value = true
  orderId.value=row.id
}
const options = [
  {
    label: '正在下单',
    value: '正在下单',
    icon: ForkSpoon
  },
  {
    label: '等待支付',
    value: '等待支付',
    icon: WalletFilled,
  },
  {
    label: '完成支付',
    value: '完成支付',
    icon: WalletFilled,
  },
  {
    label: '正在制作',
    value: '正在制作',
    icon: Bowl,
  },
  {
    label: '正在配送',
    value: '正在配送',
    icon: Bicycle,
  },
  {
    label: '订单已完成',
    value: '订单已完成',
    icon: SuccessFilled,
  },
  {
    label: '已退款',
    value: '已退款',
    icon: Wallet,
  },
]

const formatDateTime = (dateTimeStr) => {
  const date = new Date(dateTimeStr);
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
};
const updateorderstatusByid = async () => {
  const response=await updateorderstatusByidservice(orderId,status1)
  if(response.code==200){
    showdiglog1.value=false
    isInitialLoad.value=false
    ElMessage.success('状态修改成功');
    await getallorderBybackground()
  }else {
    ElMessage.error('状态修改失败');
  }
}

const getallorderBybackground = async () => {
  const response=await getallorderBybackgroundservice();
  if(response.code==200){
    isInitialLoad.value=true
    tableData.length=0
    response.date.forEach((order) => {
order.ordertime=formatDateTime(order.ordertime)
      if(order.status.includes('正在下单')){
        order.color='blue'
      }
      if(order.status.includes('等待支付')){
        order.color='blue'
      }
      if(order.status.includes('完成支付')){
        order.color='blue'
        order.status='完成支付'
      }
      if(order.status.includes('正在制作')){
        order.color='blue'
        order.status='正在制作'
      }
      if( order.status.includes('正在配送')){
        order.color='blue'
        order.status='正在配送'
      }
      if( order.status.includes('订单已完成')){
        order.color='green'
        order.status='订单已完成'
      }
      if(order.status.includes('已退款')){
        order.color='red'
        order.status='已退款'
      }
      tableData.push(order)
    })

  }

}
const currentPageItems = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  return tableData.slice(startIndex, endIndex);
});
const totalItems = computed(() => tableData.length);

const showitem = (id) => {
  showdiglog3.value=true
  orderId.value=id.value

}
const showdiglogbutton = (row) => {
  showdiglog1.value=true
  orderId.value=row.id
}
const sendmessage=async ()=>{
  const response=await sendmessageTouserservice(message.value,userid.value,orderId.value)
  if(response.code==200){
    showdiglog2.value=false
    ElMessage.success('发送成功');
  }else {
    ElMessage.error('发送失败');
  }
}

onMounted(()=>{
  getallorderBybackground()

})
watch(
    () => tableData.map(item => item.status),
    (newStatuses, oldStatuses) => {
      if (oldStatuses && oldStatuses.length > 0) {
        console.log(newStatuses, oldStatuses);
        newStatuses.forEach((newStatus, index) => {
          const oldStatus = oldStatuses[index];
          if (oldStatus !== newStatus) {
            const newItem = tableData[index];
            // 状态发生变化时，更新 message、orderId 和 userid，并发送消息
            message.value = newItem.status;
            orderId.value = newItem.id;
            userid.value = newItem.userId;
            sendmessage();
          }
        });
      }
    },
    { deep: true, immediate: true }
);

const deletorderandorderdetailByorderId = async (orderid) => {
  const response = await deletorderandorderdeTaliByorderIDservice(orderid)
  if (response.code === 200) {
    centerDialogVisible.value = false
    await getallorderBybackground()
    ElNotification({
      title: 'Title',
      message: h('i', {style: 'color: teal'}, '取消订单成功'),
    })
    console.log(response.message)
  } else {
    console.log(response.message)
  }

}
const getorder = async (row) => {
  showdiglog3.value=true
  const response=await getaplyedorderdetaibyorderIdservice(row.id)
  if(response.code===200){
    items.length=0
    response.date.forEach(item => {
      items.push(item);
    });
    console.log(items)
  }

}
</script>

<style scoped>
.el-button1{
  margin-left: 12px;
}
</style>